<?php

namespace common\widgets\grid;

use Yii;
use yii\base\Widget;
use yii\helpers\Html;

class BulkAjaxActionBtn extends Widget
{
    public $btnId;
    public $label;
    public $gridViewId;
    public $url;
    public $method;
    public $refresh = true;

    const AJAX_STATUS_SUCCESS = 1;
    const AJAX_STATUS_ERROR = -1;

    public static function ajaxReturnSuccess($msg = "", $code = self::AJAX_STATUS_SUCCESS, $data = [])
    {
        return self::ajaxReturn(['msg' => $msg, 'code' => $code, 'data' => $data]);
    }

    public static function ajaxReturnError($msg = "", $code = self::AJAX_STATUS_ERROR, $data = [])
    {
        return self::ajaxReturn(['msg' => $msg, 'code' => $code, 'data' => $data]);
    }

    protected static function ajaxReturn($result)
    {
        return json_encode($result);
    }

    /**
     * {@inheritdoc}
     */
    public function init()
    {
        parent::init();
        $this->renderBtn();
    }

    public function renderBtn()
    {
        $csrf = Yii::$app->request->csrfToken;
        $this->refresh = $this->refresh ? 1 : 0;
        $view = $this->getView();
        echo Html::a($this->label, '#', ['id' => $this->btnId]);
        $view->registerJs("
            jQuery('#{$this->btnId}').on('click',function(){
                var keys = $('#{$this->gridViewId}').yiiGridView('getSelectedRows');
                if(keys.length > 0 ){
                    if(confirm('确定对下列对象执行 {$this->label} 操作 ?' + '\\n' + keys)){
                        jQuery.post('{$this->url}',{'keys':keys,'_csrf':'{$csrf}'},function(r){
                            alert(r.msg);
                            if({$this->refresh}){
                                window.location.reload(true);
                            }
                        },\"json\");
                    }
                }else{
                    alert('未选中任何数据项.');
                }
            });
        ");
    }
}